import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material';
import { SelectionModel } from '@angular/cdk/collections';
import { AuthGuardService } from '../../service/AuthGuardService';
import { ForumService } from '../../service/ForumService';
import { ConfirmDialogComponent } from '../confirmDialog/confirmDialog';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Forum } from '../../models/Forum';
import { NewsCategory } from '../../models/NewsCategory';
import { Subscription } from 'rxjs/index';
import { environment } from '../../environments/environment';
import { filter } from 'rxjs/operators';
import { EditorComponent } from '../editor/editor';
import { ManageArticleComponent } from '../manageArticle/manageArticle';
import {Location} from '@angular/common';

@Component({
  templateUrl: './forum.html',
  styleUrls: ['./forum.css'],
})
export class ForumComponent implements OnInit {
  selection: SelectionModel<Forum>;
  cols = ['select', 'title', 'content', 'type', 'author', 'pubdate'];
  forums: Forum[];
  total: number;
  subscriptions: Subscription[] = [];
  pageSize = environment.pageSize;
  page = 0;
  isAdmin: boolean;
  categorys: NewsCategory[];

  constructor(
    private dialog: MatDialog,
    private route: ActivatedRoute,
    private router: Router,
    private authGuardService: AuthGuardService,
    private  forumService: ForumService
  ) { }

  ngOnInit() {
    this.authGuardService.checkAdmin().subscribe((isAdmin: boolean) => {
      this.isAdmin = isAdmin;
      if (this.isAdmin) {
        this.cols = [ 'title', 'content', 'type', 'author', 'pubdate', 'operate'];
      } else {
        this.cols = this.cols.filter(col => col  !== 'operate');
      }
    });
    this.subscriptions[1] = this.route.data.subscribe((data: {
      results: { forums: Forum[], total: number},
      categorys: NewsCategory[],
    }) => {
      this.forums = data.results.forums;
      this.categorys = data.categorys;
      this.total = data.results.total;
    });
    const initialSelection = [];
    const allowMultiSelect = true;
    this.selection = new SelectionModel<Forum>(allowMultiSelect, initialSelection);
  }

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.forums.length;
    return numSelected === numRows;
  }

  allToggle() {
    this.isAllSelected() ?
      this.selection.clear() :
      this.forums.forEach(row => this.selection.select(row));
  }
  onManageArticle() {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(ManageArticleComponent, {
        width: '600px',
        height: '700px',
        data: {
          categorys: this.categorys
        }
      });
      dialogRef.afterClosed().subscribe((result) => {
        this.update({pageIndex: 0, pageSize: this.pageSize});
      });
    });
  }
  onOpenAdd() {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(EditorComponent, {
        width: '600px',
        height: '700px',
        data: {
          categorys: this.categorys,
          forum: {}
        }
      });
      dialogRef.afterClosed().subscribe((result) => {
        this.update({pageIndex: 0, pageSize: this.pageSize});
      });
    });
  }

  onOpenEdit(forum: Forum) {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(EditorComponent, {
        width: '600px',
        height: '700px',
        data: {
          forum: forum,
          categorys: this.categorys
        }
      });
      dialogRef.afterClosed().subscribe((result) => {
        this.update({pageIndex: 0, pageSize: this.pageSize});
      });
    });
  }

  onDelete(id: number) {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(ConfirmDialogComponent, {
        width: '400px',
        height: '200px',
        data: {message: '确认删除？'}
      });
      dialogRef.afterClosed().subscribe((result) => {
        if (result) {
          this.forumService.deleteForum(id).subscribe((res) => {
            if (res.success) {
              this.update({pageIndex: 0, pageSize: this.pageSize});
            }
          });
        }
      });
    });
  }

  update(event: {pageIndex: number, pageSize: number}) {
    this.forumService.getForums(event.pageIndex, event.pageSize).subscribe((res) => {
      this.forums = res.res;
      this.total = res.total;
      this.page = event.pageIndex;
    });
  }

  trackById(index: number, item: any) {
    return item.id;
  }
}
